package com.damon.dm_mail.controller;

import com.damon.dm_mail.mail.MailConfig;
import com.damon.dm_mail.pojo.Email;
import com.damon.dm_mail.pojo.Sender;
import com.damon.dm_mail.pojo.SenderCounter;
import com.damon.dm_mail.pojo.UserInfo;
import com.damon.dm_mail.service.MailService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.ResourceUtils;
import org.springframework.util.StringUtils;

import javax.mail.MessagingException;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.List;

@Component("scheduler")
public class ScheduleTask {
    private static final Logger log = LoggerFactory.getLogger(ScheduleTask.class);
    @Autowired
    private JavaMailSenderImpl mailSender;
    @Autowired
    private MailService mailService;
    @Autowired
    private MailConfig mailConfig;
    //从id是1的开始发送
    private int lastId = 1;

    //间隔5分钟发送一次
    @Scheduled(initialDelay = 1000, fixedDelay = 1000 * 60 * 2)
    public void sendEmailCron() {
        //取得一个接收者
        SenderCounter senderCounter = mailService.getLastIndex();
        if (senderCounter != null) {
            lastId = senderCounter.getLastIndex();
        }
        UserInfo userInfo = mailService.queryUserInfoById(lastId);
        if (userInfo == null) {
            log.info("未查询到接收者-获取下一条接收者!------over!");
            lastId++;
            mailService.saveLastIndex(lastId);
            return;
        }
        //随机取出某几条发送者
        List<Sender> senderList = mailService.queryAllSender();
        if (senderList.size() <= 0) {
            log.info("未查询到发送者!------over!");
            return;
        }
        //发送者
        Sender sender = senderList.get(0);

        String text = "";
        File file = null;
        try {
            List<Email> emails = mailService.queryAllEmail();
            if (emails.size()<=0){
                return;
            }
            //发送第一条email
            Email email = emails.get(0);
//            file = ResourceUtils.getFile("classpath:mail.html");
//            text = FileUtils.readFileToString(file, "utf-8");
            text = email.getContent();
            if (text == null || text.equalsIgnoreCase("")) {
                log.info("发送内容为空!------over!");
                return;
            }
            String[] arr = StringUtils.split(sender.getEmail(), "@");
            if (arr.length == 2) {
                String str = arr[1];
                System.out.println(str);
                mailConfig.sendEmail(mailSender, str, sender, userInfo, email);
                log.info("发送者：" + sender.getEmail() + "\t 接收者：" + userInfo.getEmail() + "===================成功");
            }
            lastId += 1;
            mailService.saveLastIndex(lastId);
        } catch (Exception e) {
            log.error("发送任务失败:\n" + e.getMessage());
            lastId += 1;
            mailService.saveLastIndex(lastId);
        }
    }


}
